<template>
  <div id="qr-page">
    <div id="back-button" @click="$router.back()">
      <i href="javascript:void(0)" class="el-icon-close"></i>
    </div>
    <div class="qr-act-shade" :style="{height:getWinSize().height+'px'}">

    </div>
  </div>
</template>

<script>
export default {
  name: 'QrPage',
  data: function () {
    return {
      barcode: false,
    }
  },
  mounted () {
    let $this=this
      $this.init()
    setTimeout(function () {
      $this.test()
    },500)
  },
  beforeDestroy () {
    if (this.myBarcode) {
      this.myBarcode.close()
    }
  },
  methods: {
    test:function () {
      // this.MyQrAct('{"event":"JoinGroupOrder","invitationCode":"127499"}')
      // this.MyQrAct('{"event":"ShopProductPurchase","orderNo":"202402281624068316"}')
    },
    init: function () {
      let $this = this
      if (typeof plus==='undefined'){
        return
      }
      var webview = plus.webview.currentWebview()
      var left = (Math.ceil(this.getWinSize().width * 0.5) - 200)
      $this.myBarcode = plus.barcode.create('barcode', [plus.barcode.QR], {
        top: '100px',
        left: left + 'px',
        width: '400px',
        height: '400px',
        position: 'static'
      })
      // 扫码成功回调
      $this.myBarcode.onmarked = function (type, result) {
        var text = '未知: '
        switch (type) {
          case plus.barcode.QR:
            text = 'QR: '
            break
          case plus.barcode.EAN13:
            text = 'EAN13: '
            break
          case plus.barcode.EAN8:
            text = 'EAN8: '
            break
        }
        $this.$forceUpdate()
        // alert('result: '+result)
        $this.MyQrAct(result)
        // alert( text+result);
      }
      //此处未演示扫码成功回调的地址设置，实际请参考HTML5Plus API自行处理
      //注意扫码区域需为正方形，否则影响扫码识别率
      webview.append($this.myBarcode)
      $this.$forceUpdate()
      $this.myBarcode.start()

      //
      // $this.getAndUsePermission('camera',function () {
      //   var codeScan = api.require('codeScan')
      //   codeScan.scan(function (ret, err) {
      //     if (ret.status) {
      //       // alert('结果是: '+JSON.stringify(ret));
      //       $this.MyQrAct(ret.code)
      //     }
      //   })
      // })
    },
    MyQrAct: function (data) {
      let $this = this
      var qrData = {}
      if (data.indexOf(dict.H5_UrlMap['H5_MEMBER_REGISTER']) > -1) {
        qrData.event = 'Register'
      } else {
        qrData = JSON.parse(data)
      }

      switch (qrData.event) {
        // 1.邀请注册
        case 'Register':
          var url = data
          var urlArr = url.split('?')
          var queryString = urlArr[1]
          var queryArr = queryString.split('&')
          var queryMap = {}
          // api.alert({msg: 'queryArr: '+JSON.stringify(queryArr)})
          queryArr.forEach(function (str, index) {
            var strArr = str.split('=')
            queryMap[strArr[0]] = strArr[1]
          })
          if ($this.CurrUser.IsLogin()) {
            $this.CurrUser.setCache(null)
            $this.$confirm('当前操作需要退出登录?', '系统提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              $this.$router.push({
                name: 'Register',
                query: {
                  invitationCode: queryMap['invitationCode']
                }
              })
            }).catch(() => {
              //
            })
          } else {
            $this.$router.push({
              name: 'Register',
              query: {
                invitationCode: queryMap['invitationCode']
              }
            })
          }
          // api.alert({msg: '邀请码: ' + queryMap['invitationCode']})
          break
        // 2.团购参与
        case 'JoinGroupOrder':
          if (!qrData.invitationCode) {
            return $this.successTip('二维码不支持: ' + JSON.stringify(qrData), 'warning')
          }
          if (!$this.CurrUser.IsLogin()){
            $this.$message.warning('参与团购，必须先进行登陆')
            $this.$router.push('/Login')
            return
          }
          $this.myBarcode.close()
          $this.bus.$emit('GroupOrderJoinDialogCallBus', {
            invitationCode: qrData.invitationCode,
            // price: data.productPrice,
          },true)
          break
        // 3.采购订单扫描,提交
        case 'ShopProductPurchase':
          // 获取采购订单信息
          // console.log('qrData',qrData)
          if (!$this.CurrUser.IsLogin()){
            $this.$message.warning('采购下单，必须先进行登陆')
            $this.$router.push('/Login')
            return
          }
          if ($this.myBarcode && $this.myBarcode.close){
            $this.myBarcode.close()
          }
          $this.checkLoginAct(function () {
            $this.MyRequest($this.ApiDoNameMember + 'Member/getShopProductPurchaseList', {orderNo: qrData.orderNo}, function (data) {
              // console.log('data',data)
              $this.$confirm('系统已经匹配到【采购订单】您是否前往提交?', '系统提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'success'
              }).then(() => {
                var shopProductPurchaseOrder = {}
                if (data.list && data.list.length > 0) {
                  shopProductPurchaseOrder = data.list[0]
                } else {
                  console.log('采购订单不存在!')
                  return $this.$message.error('采购订单不存在!')
                }
                // console.log('shopProductPurchaseOrder',shopProductPurchaseOrder)
                // [{"image":"http://image.yangfankj.com/product/103/0.jpg","price":215.00,"name":"德国欧莱德-磨角机","model":"常规","id":8,"nums":1},{"image":"http://image.yangfankj.com/product/105/0.jpg","price":195.00,"name":"东成-气动直钉枪","model":"常规","id":11,"nums":5}]
                var tmpProductList = shopProductPurchaseOrder.productData
                var confirmOrderData = {
                  shop: {
                    id: shopProductPurchaseOrder.shopId,
                    name: shopProductPurchaseOrder.shopName,
                    logo: shopProductPurchaseOrder.shopLogo,
                  },
                  productList: []
                }
                tmpProductList.forEach(function (product, index) {
                  confirmOrderData.productList.push({
                    id: product.shopProductStockId,
                    shopProductId: product.id,
                    shopProductName: product.name,
                    price: product.price,
                    image: product.image,
                    model: product.model,
                    nums: product.nums
                  })
                })

                // 存储: 店铺数据,商品数据
                localStorage.setItem('selectProductData', JSON.stringify(confirmOrderData))
                // 跳转至-订单确认页面
                $this.$router.push({
                  name: 'ConfirmOrder',
                  query: {
                    type: 'shopProductPurchase',
                    orderNo: shopProductPurchaseOrder.orderNo
                  }
                })
              }).catch(() => {
                $this.$router.back()
              })

            }, function () {

            })
          })
          break
        // 4.绑定店铺
        case 'BindingShop':
          if (!$this.CurrUser.IsLogin()){
            $this.$message.warning('绑定店铺，必须先进行登陆')
            $this.$router.push('/Login')
            return
          }
          $this.myBarcode.close()
          $this.MyRequest($this.ApiDoNameMember + 'Member/bindingShop', {qrCode: qrData.qrCode}, function (data) {
            $this.successTip('绑定店铺成功!')
            $this.$router.push('/MemberBindingShopList')
            $this.bus.$emit('UserLoginCallBus')
          },function (res) {
            $this.$message.warning(res.message)
            $this.$router.back()
          })
          break
      }
    }
  }
}
</script>

<style scoped>
#qr-page{
  position: relative;
}
#qr-page #back-button{
  display: inline-block;
  width: 50px;
  height: 50px;
  position: fixed;
  z-index: 1000;
  text-align: center;
  top: 10px;
  right: 10px;
}
#qr-page #back-button i{
  color: #EEEEEE;
  font-size: 28px;
}
#qr-page .qr-act-shade {
  position: fixed;
  width: 100%;
  height: 600px;
  background: #000000;
  z-index: 999;
  left: 0px;
  top: 0px;
}
</style>
